package com.xdq.educenter.controller;


import com.xdq.commonutils.JwtUtils;
import com.xdq.commonutils.R;
import com.xdq.commonutils.user.UcenterMemberOrder;
import com.xdq.educenter.entity.UcenterMember;
import com.xdq.educenter.entity.vo.RegisterVo;
import com.xdq.educenter.service.UcenterMemberService;
import com.xdq.servicebase.exceptionhandler.GuliException;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

/**
 * <p>
 * 会员表 前端控制器
 * </p>
 *
 * @author atguigu
 * @since 2024-09-22
 */
@RestController
@RequestMapping("/educenter/member")
@CrossOrigin
public class UcenterMemberController {

    @Autowired
    private UcenterMemberService memberService;

    @PostMapping("login")
    public R loginUser(@RequestBody UcenterMember member) {
        String token = null;
        try {
            token = memberService.login(member);
            return R.ok().data("token", token);
        } catch (GuliException e) {
            return R.error().message(e.getMessage());
        }
    }

    @GetMapping("testfegin")
    public R testfegin(HttpServletRequest request) {
        return R.ok().data("testfegin", "testfegin");
    }

    @PostMapping("register")
    public R registerUser(@RequestBody RegisterVo registerVo) {
        try {
            memberService.register(registerVo);
            return R.ok();
        } catch (GuliException e) {
            return R.error().message(e.getMessage());
        }
    }

    @GetMapping("getMemberInfo")
    public R getMemberInfo(HttpServletRequest request) {
        System.out.println("getMemberInfo======");
        System.out.println("request: " + request);
        System.out.println("token: " + request.getHeader("token"));
        String memberId = JwtUtils.getMemberIdByJwtToken(request);
        System.out.println("memberId: " + memberId);
        if (StringUtils.isEmpty(memberId)) {
            return R.error().message("需要token");
        }
        UcenterMember member = memberService.getById(memberId);
        return R.ok().data("userInfo", member);
    }


    @PostMapping("getUserInfoOrder/{id}")
    public UcenterMemberOrder getUserInfoOrder(@PathVariable String id) {
        UcenterMember member = memberService.getById(id);
        UcenterMemberOrder ucenterMemberOrder = new UcenterMemberOrder();
        BeanUtils.copyProperties(member, ucenterMemberOrder);
        return ucenterMemberOrder;
    }

    // 查询某一天注册人数
    @GetMapping("countRegister/{day}")
    public R countRegister(@PathVariable String day) {
        Integer count = memberService.countRegisterDay(day);
        return R.ok().data("countRegister", count);
    }
}

